﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
using Calculation = Sunboxsoft.ASMS.Client.Domain.Calculation;
namespace Sunboxsoft.ASMS.Client.UI.Dispatching
{
    /// <summary>
    /// 维修单详细信息
    /// </summary>
    public partial class MaintenanceBillDetailView : UserControl, IView
    {
        /// <summary>
        /// 维修单号
        /// </summary>
        private Guid Id;
        /// <summary>
        /// 维修单详细信息
        /// </summary>
        WebRef.MaintenanceBillDetail billDetail = null;

        Promise _promise = new Promise();

        public MaintenanceBillDetailView()
        {
            InitializeComponent();
        }

        public MaintenanceBillDetailView(Guid Id)
            : this()
        {
            this.Id = Id;
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("back", Resources.isBack, "返回", btnBack_Click))
               .AddAction(new ActionNode("dispatching", Resources.isDispatchingOrderList, "派工施工", btnDispact_Click) { IsShow = false })
               .AddAction(new ActionNode("getMaterial", Resources.isGetMaterial, "领料退料", btnGetMaterail_Click) { IsShow = false })
               .AddAction(new ActionNode("settling", Resources.isSettling, "订单结算", btnSettleMent_Click) { IsShow = false })
               .AddAction(new ActionNode("checkedOut", Resources.isSettling, "订单收银", btnCheckedOut_Click) { IsShow = false })
               .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", btnRefresh_Click));
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                BindData();
            }
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(BindData).Run();

        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("维修单详细信息");
        }
        #endregion

        #region Method
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindData()
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.MaintenanceBillDetail> result = new Service.GetService().GetMaintenanceBill(Id);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        this.billDetail = result.Data;
                        this.TabPageServiceProject.Text = string.Format("服务项目({0}项)", result.Data.Bill.ServiceItemCount.ToString());
                        this.TabPageGoods.Text = string.Format("商品/配件({0}项)", result.Data.Bill.MaterialCount.ToString());
                        this.TabPageOther.Text = string.Format("其他收费/优惠({0}项)", result.Data.Bill.PayItemCount.ToString());

                        this.lblInfo.Text = string.Format("订单编号：{0}-创建时间：{1}", result.Data.Bill.Number, result.Data.Bill.CreatedTime);
                        this.txtBookingBillId.Text = result.Data.Bill.BookingBillNumber;
                        this.txtSalesManagerName.Text = result.Data.Bill.SalesManagerName;
                        if (result.Data.Bill.EstimatedDeliveryDate != null)
                        {
                            this.txtEstimatedDeliveryDate.Text = result.Data.Bill.EstimatedDeliveryDate.Value.ToString("yyyy/MM/dd");
                        }
                        this.txtCustomerName.Text = result.Data.Bill.CustomerName;
                        this.txtCustomerTelephone.Text = result.Data.Bill.CustomerTelephone;
                        this.txtLPN.Text = result.Data.Bill.LPN;
                        this.txtVIN.Text = result.Data.Bill.VIN;
                        this.txtEIN.Text = result.Data.Bill.EIN;
                        this.txtOilMass.Text = result.Data.Bill.OilMass.ToString();
                        this.txtRunningKilometers.Text = result.Data.Bill.RunningKilometers.ToString();
                        this.txtMemo.Text = result.Data.Bill.Memo;
                        this.txtAmount.Text = result.Data.Bill.Amount.ToString();
                        for (int i = 0; i < result.Data.ServiceItemList.Length; i++)
                        {
                            billDetail.ServiceItemList[i].ActualTechnicianName = result.Data.ServiceItemList[i].ActualTechnicianName != null ? result.Data.ServiceItemList[i].ActualTechnicianName : result.Data.ServiceItemList[i].TechnicianName;
                        }
                        this.GCServiceProject.DataSource = result.Data.ServiceItemList;
                        for (int i = 0; i < result.Data.MaterialList.Length; i++)
                        {
                            billDetail.MaterialList[i].WarehouseId = result.Data.MaterialList[i].ActualWarehouseId != null ? result.Data.MaterialList[i].ActualWarehouseId : result.Data.MaterialList[i].WarehouseId;
                        }
                        this.GCGoodsData.DataSource = result.Data.MaterialList;
                        this.GCOther.DataSource = result.Data.PayItemList;

                        string strOutMess = "";
                        decimal total = Calculation.MaintanceBillCalculation.Calc(
                            result.Data.ServiceItemList == null ? null : result.Data.ServiceItemList.ToArray(),
                            result.Data.MaterialList == null ? null : result.Data.MaterialList.ToArray(),
                            result.Data.PayItemList == null ? null : result.Data.PayItemList.ToArray(),
                            true,
                            out strOutMess);

                        this.ctllblSettlementBillTextInfo.Text = strOutMess;
                        this.ctllblSettlementBillTotal.Text = string.Format("应收金额：{0}", Math.Round(total, 2).ToString());

                        if (!result.Data.IsAllServiceItemFinished())
                        {
                            this.ShowAction("dispatching", true);
                        }
                        if (!result.Data.IsAllMaterialFinished())
                        {
                            this.ShowAction("getMaterial", true);
                        }
                        switch (result.Data.Bill.Status)
                        {
                            case Domain.Constant.MaintenanceBillStatus.WaitSettling:
                                this.ShowAction("settling", true);
                                break;
                            case Domain.Constant.MaintenanceBillStatus.WaitCheckOut:
                                this.ShowAction("checkedOut", true);
                                break;
                        }
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                    this.HideMask();
                }));
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, "Detail");
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, object e)
        {
            BindData();
        }
        /// <summary>
        /// 派工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDispact_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillDispatchView(billDetail));
        }
        /// <summary>
        /// 领料退料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetMaterail_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillMaterialView(billDetail));
        }
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSettleMent_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillSettlementView(billDetail));
        }
        /// <summary>
        /// 收银
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheckedOut_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new CheckOut.CheckOutSettlementBillView(billDetail.Bill.Id, "Maintenance"));
        }
        /// <summary>
        /// 车辆出厂
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCarOutClick(object sender, object e)
        {
            if (UIContext.Current.ViewManager.ShowQuestion("确定要出厂吗？"))
            {
                UIContext.Current.InvokeAsync(() =>
                {
                    ServiceResult result = new Service.DeliverService().DeliverMaintenanceBill(Id);
                    this.BeginInvoke(new Action(() =>
                    {
                        if (result.IsSuccess)
                        {
                            UIContext.Current.ViewManager.CloseView(true, null);
                            _promise.Resolve();

                        }
                        else
                        {
                            UIContext.Current.ViewManager.ShowError(result.Message);
                            _promise.Reject();
                        }
                    }));
                });
            }
        }
        #endregion
    }
}
